package com.chucknorris.android.ui;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Locale;
import java.util.Random;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chucknorris.android.R;
import com.chucknorris.android.db.ChuckColumns;
import com.chucknorris.android.db.ChuckQuery;
import com.chucknorris.android.model.Chuck;
import com.chucknorris.android.util.LocaleUtils;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;

public class ChuckActivity extends GAActivity implements LoaderManager.LoaderCallbacks<Cursor>, OnClickListener {

	public static final String SEED = "seed";
	public static final String RU = "ru";
	public static final String LOCALE = "locale";
	public static final String APP_ID = "355928411099892";
	public static final String ADS_ID = "a14f0873cd3fadf";
	private ProgressDialog progress;
	private TextView topic;
	private ImageView image;
	private ImageView ruLocale;
	private ImageView usLocale;
	private Cursor mCursor;
	private long id = 0;
	private int isLike = 0;
	private int count = 0;
	private Random generator = new Random();
	private static final int ID_ITEM = 1;
	private Facebook mFacebook;
	private static String[] PERMISSIONS = new String[] { "offline_access", "read_stream", "publish_stream" };

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		topic = (TextView) findViewById(R.id.topic);
		image = (ImageView) findViewById(R.id.chuck_like);
		ruLocale = (ImageView) findViewById(R.id.ru_locale);
		usLocale = (ImageView) findViewById(R.id.en_locale);
		ruLocale.setOnClickListener(this);
		usLocale.setOnClickListener(this);

		Bundle bundle = new Bundle();
		if (!RU.equals(LocaleUtils.getCurrentLocale())) {
			bundle.putString(LOCALE, Locale.US.getLanguage());
		} else {
			bundle.putString(LOCALE, RU);
		}
		getSupportLoaderManager().initLoader(ChuckQuery._TOKEN, bundle, this);

		LinearLayout layout = (LinearLayout) findViewById(R.id.ads);
		AdView adView = new AdView(this, AdSize.BANNER, ADS_ID);
		layout.addView(adView);
		AdRequest request = new AdRequest();
		// request.setTesting(true);
		adView.loadAd(request);

	}

	public void share(View view) {
		Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
		shareIntent.setType("text/plain");
		shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getText(R.string.watch_for));
		shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, topic.getText().toString().trim());
		startActivity(Intent.createChooser(shareIntent, getText(R.string.choose_service)));
	}

	public void onLike(View view) {
		mFacebook = new Facebook(APP_ID);
		authorizeAndLike(ChuckActivity.this);
	}

	public void addToFavorite(View view) {
		ContentValues values = new ContentValues();
		int islikeNewValue = (isLike == 0) ? 1 : 0;
		values.put(ChuckColumns.ISLIKE.getName(), islikeNewValue);
		if (1 == getContentResolver().update(Chuck.CONTENT_URI, values, ChuckColumns._ID.getName() + " =? ", new String[] { String.valueOf(id) })) {
			changeChuckImage(islikeNewValue);
			isLike = islikeNewValue;
			mCursor.requery();
		}
	}

	public void openList(View view) {
		Intent intent = new Intent(ChuckActivity.this, ListFavourtesActivity.class);
		startActivityForResult(intent, ID_ITEM);

	}

	public void nextTopic(View view) {
		int randomPosition = generator.nextInt(count);
		mCursor.moveToPosition(randomPosition);
		switchToNextTopic();
	}

	private void switchToNextTopic() {
		isLike = mCursor.getInt(ChuckQuery.ISLIKE);
		id = mCursor.getLong(ChuckQuery._ID);
		// try {
		// topic.setText(SimpleCrypto.decrypt(SEED,
		// mCursor.getString(ChuckQuery.TOPIC)));
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		topic.setText(mCursor.getString(ChuckQuery.TOPIC));
		changeChuckImage(isLike);
	}

	private void changeChuckImage(int value) {
		switch (value) {
		case 0:
			image.setImageResource(R.drawable.chuck_not_cheched1);
			break;
		case 1:
			image.setImageResource(R.drawable.chuck_cheched1);
			break;

		default:
			break;
		}
	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
		switch (id) {
		case ChuckQuery._TOKEN:
			if (bundle != null && bundle.containsKey(LOCALE)) {
				progress = ProgressDialog.show(this, getString(R.string.loading), getString(R.string.please_wait), true, false);
				String locale = bundle.getString(LOCALE);
				return new CursorLoader(ChuckActivity.this, Chuck.CONTENT_URI, ChuckQuery.PROJECTION, ChuckColumns.LOCALE + " = '" + locale + "'", null,
						Chuck.DEFAULT_SORT);
			}
		default:
			return null;
		}

	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		switch (loader.getId()) {
		case ChuckQuery._TOKEN:
			if (progress != null)
				progress.dismiss();
			mCursor = cursor;
			count = mCursor.getCount();
			nextTopic(null);
			break;
		default:
			break;
		}

	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		switch (loader.getId()) {
		case ChuckQuery._TOKEN:
			break;
		default:
			break;
		}

	}

	@Override
	protected void onActivityResult(int reqCode, int resultCode, Intent data) {
		super.onActivityResult(reqCode, resultCode, data);
		Log.e("reqCode", "" + reqCode);
		switch (reqCode) {
		case ID_ITEM:
			if (data != null) {
				long id = data.getLongExtra("id", 0L);
				if (mCursor.moveToFirst()) {
					do {
						if (id == mCursor.getLong(ChuckQuery._ID))
							break;
					} while (mCursor.moveToNext());
				}
				switchToNextTopic();
			}
			break;

		default:
			mFacebook.authorizeCallback(reqCode, resultCode, data);
			break;
		}
	}

	private void authorizeAndLike(Activity activity) {
		mFacebook.authorize(activity, PERMISSIONS, new DialogListener() {
			@Override
			public void onComplete(Bundle values) {
				Log.v("TAG", "onComplete");
				new LikePostedMessage().execute("");
			}

			@Override
			public void onFacebookError(FacebookError error) {
				Log.v("TAG", "onFacebookError");
				Toast.makeText(ChuckActivity.this, "Facebook Like did fail!", Toast.LENGTH_LONG).show();
			}

			@Override
			public void onError(DialogError e) {
				Log.v("TAG", "onError");
				Toast.makeText(ChuckActivity.this, "Facebook Like did fail!", Toast.LENGTH_LONG).show();
			}

			@Override
			public void onCancel() {
				Log.v("TAG", "onCancel");
			}

		});
	}

	private class LikePostedMessage extends AsyncTask<String, Void, Integer> {
		@Override
		protected Integer doInBackground(String... params) {
			String response = "";
			Integer code = 0;
			try {
				String imageUrl = "http://dl.dropbox.com/u/20432838/Chuck/chuck.jpg";//

				Bundle bundle = new Bundle();
				bundle.putString("message", topic.getText().toString().trim());
				bundle.putString("picture", imageUrl);
				bundle.putString("name", getString(R.string.watch_for));
				bundle.putString("link", "https://market.android.com/details?id=com.chucknorris.android");
				bundle.putString("caption", getString(R.string.app_name));

				response = mFacebook.request("me/feed", bundle, "POST");
				Log.v("FaceBook_Response", response);
				try {
					JSONObject json = new JSONObject(response);
					if (!json.isNull("id")) {
						String id = json.getString("id");
						response = mFacebook.request(id + "/likes", new Bundle(), "POST");
						if (response.equalsIgnoreCase("true")) {
							code = 1;
						}
					}
				} catch (JSONException e) {
					code = 0;
					e.printStackTrace();
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
				code = 0;
			} catch (IOException e) {
				e.printStackTrace();
				code = 0;
			}
			return code;
		}

		@Override
		protected void onPostExecute(Integer result) {
			if (result == 1) {
				Toast.makeText(getApplicationContext(), "Facebook Like success!", Toast.LENGTH_LONG).show();
			} else if (result == 0) {
				Toast.makeText(getApplicationContext(), "Facebook Like did fail!", Toast.LENGTH_LONG).show();
			}
			super.onPostExecute(result);
		}
	}

	@Override
	public void onClick(View v) {
		getSupportLoaderManager().destroyLoader(ChuckQuery._TOKEN);
		switch (v.getId()) {
		case R.id.ru_locale:
			LocaleUtils.changeLocale(ChuckActivity.this, RU);
			break;
		case R.id.en_locale:
			LocaleUtils.changeLocale(ChuckActivity.this, Locale.US.getLanguage());
			break;
		default:
			break;
		}
		finish();
		Intent intent = new Intent(ChuckActivity.this, ChuckActivity.class);
		startActivity(intent);

	}
}
